package com.bs.web.controller;

import cn.hutool.core.io.IoUtil;
import com.bs.vo.RestResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 说明：
 *
 * @author 琪
 * @since 2025/5/8 20:21
 */
@RestController
@RequestMapping("/file")
@Api(tags = "文件接口")
@Slf4j
public class FileController {

    private final String uploadDir = "upload";

    /**
     * 上传图片，返回图片地址
     */
    @PostMapping("/upload")
    @ApiOperation("上传图片")
    public RestResultVo<String> upload(MultipartFile file, HttpServletRequest request) {
        //  上传图片，返回图片地址
        String fileName = file.getOriginalFilename();
        File dest = new File(uploadDir + "/" + fileName);
        try {
            InputStream inputStream = file.getInputStream();
            if (!dest.getParentFile().exists()) {
                boolean mkdirs = dest.getParentFile().mkdirs();
                log.info("创建目录：{}", mkdirs);
            }
            FileOutputStream fileOutputStream = new FileOutputStream(dest);
            IoUtil.copy(inputStream, fileOutputStream);
            IoUtil.close(inputStream);
            IoUtil.close(fileOutputStream);
            log.info("上传成功，文件路径：{}", dest.getAbsolutePath());
            String downloadUrl = "/file/download?fileName=" + fileName;
            return RestResultVo.ok(downloadUrl);
        } catch (IOException e) {
            throw new RuntimeException("上传失败", e);
        }
    }

    @GetMapping("/download")
    @ApiOperation("下载图片")
    public void download(String fileName, HttpServletResponse response) {
        //  下载图片，返回图片地址
        File file = new File(uploadDir + "/" + fileName);
        if (file.exists()) {
            response.setContentType("image/jpeg");
            // 有此头，浏览器会直接下载，没有此头，浏览器会直接打开
            // response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                IoUtil.copy(fileInputStream, response.getOutputStream());
                log.info("下载成功，文件路径：{}", file.getAbsolutePath());
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        throw new RuntimeException("文件不存在");
    }

}
